package org.goldfish.cookied_chatroom02.database;

import jakarta.servlet.ServletContext;
import org.goldfish.cookied_chatroom02.dao.DaoManager;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

class ConnectionPool {
    private final BlockingDeque<Connection> connections;
    private final Properties properties;

    ConnectionPool(ServletContext context) throws IOException, SQLException, ClassNotFoundException {
        this(context,3);
    }

    ConnectionPool(ServletContext context,int maxConnections) throws IOException, SQLException, ClassNotFoundException {
        connections = new LinkedBlockingDeque<>(maxConnections);
        properties = load(context);
        for (int count = 0; count < maxConnections; count++) {
            String URL=URL_parse();
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection= DriverManager.getConnection(URL,properties);
            connections.add(connection);
        }
    }

    @NotNull
    private String URL_parse() {
        String IP = Objects.requireNonNull(properties).getProperty("IP");
        return properties.getProperty("url").replace("<server-ip>", IP);
    }

    @NotNull
    private Properties load(@NotNull ServletContext context) throws IOException {
        Properties properties = new Properties();
        String path = ("/resources/mysql.properties");
        try (InputStream inputStream = context.getResourceAsStream(path)) {
            properties.load(inputStream);
        }
        return properties;
    }

    public Connection take() throws InterruptedException {
        return connections.take();
    }
    public void returnConnection(Connection connection){
        connections.add(connection);
    }

    public void closeAll() throws SQLException {
        while (!connections.isEmpty()){
            try {
                connections.take().close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
